<?php
/**
 * This is just a quick "Model" I threw together for a demo. Hopefully you can
 * come up with something a little more clever than this. 
 */

class Person {
	
    public function __construct() {
        $this->dao = new SQLiteDatabase(MODEL_DIR .'/db.sqlite');
        
        // create table if it doesn't exist
        $q = $this->dao->query("PRAGMA table_info(persons)");
        
        if ($q->numRows() < 1) {
            $this->dao->queryExec("CREATE TABLE persons (
            	id INT NOT NULL PRIMARY KEY,
            	spouse_id INT,
            	firstName VARCHAR(255),
            	lastName VARCHAR(255),
            	gender VARCHAR(3),
            	birthDate DATE,
            	deathDate DATE)");
        }
    }
    
    public function Save() {      
        if ($this->id) {
            $this->dao->queryExec("UPDATE persons SET 
            	firstName = '{$this->firstName}', 
            	lastName = '{$this->lastName}',
            	gender = '{$this->gender}',
            	birthDate = '{$this->birthDate}',
            	deathDate = '{$this->deathDate}'");
        } else {
            $id = uniqid();
            $this->dao->queryExec("INSERT INTO persons 
                (id, firstName, lastName, gender, birthDate, deathDate)
                 VALUES (
                 '{$id}',
            	'{$this->firstName}',
            	'{$this->lastName}',
            	'{$this->gender}',
            	'{$this->birthDate}',
            	'{$this->deathDate}')");
        }
    }
    
    public function GetById($id) {   
        $q = $this->dao->query("SELECT * FROM persons WHERE id = '{$id}'");

        if ($q->valid()) {
            return $q->current();
        } else {
            return false;
        }
    }
    
    public function GetList() {
        $q = $this->dao->query("SELECT * FROM persons");

        $results = array();
        
        while ($q->valid()) {
            $results[] = $q->current();            
            $q->next();
        }
        
        return $results;
    }
    
    public function Delete($id) {
        $this->dao->queryExec("DELETE FROM persons WHERE id='{$id}'");
    }
    
    public $id;
    public $firstName;
    public $lastName;
    public $gender;
    public $birthDate;
    public $deathDate;
    public $spouse;
    
    protected $dao;
}

?>
